﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;


namespace TravelSite.Account
{
    public partial class Login : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginUser.LoggingIn += new LoginCancelEventHandler(LoginUser_LoggingIn);
            LoginUser.LoginError += LoginUser_LoginError;
            LoginUser.Authenticate += LoginUser_Authenticate;

            if (!IsPostBack)
            {
                if (this.Request.Cookies["email"] != null && !string.IsNullOrEmpty(Request.Cookies["email"].Value))
                {
                    this.LoginUser.UserName = Request.Cookies["email"].Value;
                    this.LoginUser.RememberMeSet = true;
                }
                DoRedirectIfLogin();
            }
        }

        private bool TryLogin()
        {
            bool result = false;
            var validateResult = Membership.ValidateUser(this.LoginUser.UserName, this.LoginUser.Password);

            if (validateResult)
            {
                var user = Membership.GetUser(this.LoginUser.UserName);

                using (var userRepo = RepositoryFactory.ResolveRepository<UserRepository>())
                {
                    var findUser = userRepo.Find((Guid)user.ProviderUserKey);

                    if (findUser == null) return result;
                    if (findUser.Deleted) return result;
                    if (!findUser.IsActive) return result;
                    
                    CurrentUserId = findUser.Id;
                    CurrentUserName = findUser.UserName;
                    result = true;
                }
            }
            return result;
        }

        private void DoRedirectIfLogin()
        {
            if (CurrentProviderUserId != null)
            {
                using (var userRepo = RepositoryFactory.ResolveRepository<UserRepository>())
                {
                    var findUser = userRepo.Find((Guid)CurrentProviderUserId);
                    
                    if (findUser == null) return;
                    if (findUser.Deleted) return;
                    if (!findUser.IsActive) return;

                    CurrentUserId = findUser.Id;
                    CurrentUserName = findUser.UserName;
                }

                if (Roles.IsUserInRole("admin"))
                    Response.Redirect("~/admin/Dashboard.aspx", endResponse: true);
                else
                    Response.Redirect("~/agent/Dashboard.aspx", endResponse: true);
            }
        }
        
        private void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            if (TryLogin())
            {
                if (LoginUser.RememberMeSet)
                {
                    var cookie = new HttpCookie("email", LoginUser.UserName);
                    cookie.Expires = DateTime.Now.AddYears(1);
                    Response.Cookies.Add(cookie);
                }
                else
                {
                    var cookie = new HttpCookie("email", String.Empty);
                    cookie.Expires = DateTime.Now.AddYears(1);
                    Response.Cookies.Add(cookie);
                }

                FormsAuthentication.SetAuthCookie(LoginUser.UserName, LoginUser.RememberMeSet);

                if (Roles.IsUserInRole(LoginUser.UserName, "admin"))
                {
                    using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
                    {
                        repo.SetAuthCode((Guid)Membership.GetUser(LoginUser.UserName).ProviderUserKey);
                    }
                    Response.Redirect("~/admin/Dashboard.aspx", endResponse: true);
                }
                else
                    Response.Redirect("~/agent/Dashboard.aspx", endResponse: true);
            }

            e.Authenticated = false;
        }

        private void LoginUser_LoginError(object sender, EventArgs e)
        {
            LoginUser.FindControl("lblError").Visible = true;
        }

        void LoginUser_LoggingIn(object sender, LoginCancelEventArgs e)
        {
        }

        public string ServerPath
        {
            get { return Server.MapPath("~/Templates/"); }
        }
    }
}
